package org.grow.jssp.service;

import org.grow.jssp.entity.JsspFile;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @Author:宿世新
 * @Dte:2022/3/14
 */
@Service
public class FileLambdaOps implements FileOperator {

    @Override
    public List<JsspFile> ops(String fileName) {
        //path和fimeName的内容是一样的，只不过File.list只需要Path类型
        Path path = Paths.get(fileName);
        System.out.println("path的值为：" + path);
        try {
            Stream<Path> allFiles = Files.list(path);
            System.out.println("------------------");
//            System.out.println(allFiles.collect(Collectors.toList()));
            //过滤掉
//            Stream<Path> pathStream = allFiles.filter((e) -> {
//                return Files.isRegularFile(e);
////                return Files.isDirectory(e);
//            });
//            //映射
//            Stream<JsspFile> jsspFileStream = pathStream.map((e) -> {
//                JsspFile jsspFile = new JsspFile();
//                try {
//                    jsspFile.setSize(Files.size(e));
//                } catch (IOException ex) {
//                    ex.printStackTrace();
//                }
//                jsspFile.setTitle(e.getFileName().toString());
//                return jsspFile;
//            });
//            System.out.println(jsspFileStream.collect(Collectors.toList()));

//            System.out.println(pathStream.collect(Collectors.toList()));
            List<JsspFile> collect = allFiles.filter((e) -> {
                return Files.isRegularFile(e);
            }).map(e -> {
                JsspFile jsspFile = new JsspFile();
                try {
                    jsspFile.setSize((int) Files.size(e));
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
                jsspFile.setTitle(e.getFileName().toString());
                return jsspFile;
            }).collect(Collectors.toList());
            return collect;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
